package com.justnow.offer;

import sun.reflect.generics.tree.Tree;

public class Solution26 {

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        treeNode.left = new TreeNode(2);
        treeNode.right = new TreeNode(3);
        treeNode.left.right = new TreeNode(5);
        treeNode.left.left = new TreeNode(7);
        treeNode.right.left = new TreeNode(11);
        treeNode.right.right = new TreeNode(10);
        TreeNode treeNode1 = new TreeNode(3);
        Solution26 solution26 = new Solution26();
        //TreeNode node = solution26.findNode(treeNode, treeNode1);


    }

/*
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        TreeNode resultNode = findNode(root1, root2);
        return false;
    }

    public TreeNode findNode(TreeNode root1, TreeNode root2) {
        if (root1 == null)
            return null;
        else if (root1.val == root2.val)
            return root1;
        else {
            TreeNode result = findNode(root1.left, root2);
            if (result == null)
                result = findNode(root1.right, root2);
            if (result != null) {
                return result;
            } else {
                return null;
            }
        }
    }
*/

    public boolean HasSubtree(TreeNode root1, TreeNode root2) {
        boolean result = false;
        //当Tree1和Tree2都不为零的时候，才进行比较。否则直接返回false
        if (root1 != null && root2 != null) {
            //如果找到了对应Tree2的根节点的点
            if (root1.val == root2.val) {
                //以这个根节点为起点判断是否包含Tree2
                result = doesTree1HaveTree2(root1, root2);
            }

            //如果找不到，那么就再去root的左儿子当作起点，去判断是否包含Tree2
            if (!result) {
                result = HasSubtree(root1.left, root2);
            }

            //如果还是找不到的，那么就再去root的右儿子当作起点，去判断是否包含Tree2
            if (!result) {
                result = HasSubtree(root1.right, root2);
            }
        }
        //返回结果
        return result;
    }

    public static boolean doesTree1HaveTree2(TreeNode node1, TreeNode node2) {

        //如果tree2已经遍历完了都能对应的上，返回true
        if (node2 == null) {
            return true;
        }

        //如果tree2还没有遍历完，tree1却遍历完了。返回false
        if (node1 == null) {
            return false;
        }

        //如果其中有一个点没有对应上，返回false
        if (node1.val != node2.val) {
            return false;
        }

        //如果根节点对应的上，那么就分别去子节点里面匹配
        return doesTree1HaveTree2(node1.left,node2.left) && doesTree1HaveTree2(node1.right, node2
        .right);

    }

}
